package cn.liyicun.cp.cpweb.service;

import cn.liyicun.cp.cpweb.base.KeyValue;
import cn.liyicun.cp.cpweb.entity.SettingInfo;
import cn.liyicun.cp.cpweb.entity.SettingInfoExample;
import cn.liyicun.cp.cpweb.mapper.SettingInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SettingInfoService extends BaseService {

    @Autowired
    private SettingInfoMapper settingInfoMapper;

    private Map<String, Map<String, String>> dataCache = new HashMap<>();


    public void clear() {

            dataCache.clear();

    }

    public String keyCache(String team, String key) {
        Map<String, String> map = mapCache(team);

        return map == null ? null : map.get(key);
    }

    public Boolean containsKeyCache(String team, String key) {
        Map<String, String> map = mapCache(team);
        return map == null ? false : map.containsKey(key);
    }

    public Map<String, String> mapCache(String team) {
        Map<String, String> datas = dataCache.get(team);
        if (datas == null) {
            List<SettingInfo> lists = listDB(team);
            datas = new HashMap<>();
            if (!lists.isEmpty()) {
                for (SettingInfo info : lists) {
                    datas.put(info.getTeamKey(), info.getTeamValue());
                }
                dataCache.put(team, datas);
            }
        }
        return datas;
    }

    public List<KeyValue> listCache(String team) {
        Map<String, String> mapDatas = mapCache(team);

        List<KeyValue> datas = new ArrayList<>();
        for (Map.Entry<String, String> info : mapDatas.entrySet()) {
            KeyValue e = new KeyValue();
            e.setValue(info.getValue());
            e.setKey(info.getKey());
            datas.add(e);
        }


        return datas;

    }

    public List<SettingInfo> listDB(String team) {
        SettingInfoExample example = new SettingInfoExample();
        example.createCriteria().andTeamIdEqualTo(team);
        return settingInfoMapper.selectByExample(example);
    }
}